<template>
  <div>
    <div class="card card-custom gutter-b example example-compact" id="tableBody">
      <div class="card-header">
        <div class="card-title">
          <span class="card-icon">              
            <i class="text-dark-50 flaticon-search-magnifier-interface-symbol"></i>
          </span>
          <h3 class="card-label"> 查询区域 </h3>
        </div>
        <div class="card-toolbar">
          <div class="example-tools justify-content-center">
            <!-- 
              <span data-toggle="tooltip" class="example-toggle"></span>
              <span data-toggle="tooltip" class="example-copy"></span> 
          -->
          </div>
        </div>
      </div>
      <div class="card-body">
          <!--查询条件-->
          <div class="m-form m-form--fit m-form--label-align-left m-form--group-seperator-dashed">
            <div class="m-portlet__body">	
              <div class="form-group m-form__group row">
                  <label class="col-form-label">姓名：</label>
                  <div class="col-lg-2">
                      <input type="text" class="form-control" v-model="searchForm.name" placeholder="请输入">
                  </div>
                  <label class="col-form-label">账号：</label>
                  <div class="col-lg-2">
                      <input type="text" class="form-control" v-model="searchForm.account" placeholder="请输入">
                  </div>
                  
                  <label class="col-form-label">类型：</label>
                  <div class="col-lg-2">
                    <input type="hidden" class="form-control" name="searchForm.account_type_id" placeholder="请输入">
                    <el-select v-model="searchForm.accountTypeIdTemp" multiple placeholder="请选择">
                        <el-option
                        v-for="item in typeList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                        </el-option>
                    </el-select>
                  </div>
                  <label class="col-form-label">类型条件：</label>
                  <div class="col-lg-2">
                    <el-select maxlength="20" v-model="searchForm.typeCondition" placeholder="请选择">
                        <el-option value="">请选择</el-option>
                        <el-option
                            v-for="item in [{value:'0',label:'并且'},{value:'1',label:'或'}]"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                  </div>
              </div>
              <div class="form-group m-form__group row">  
                  <label class="col-form-label">状态：</label>
                  <div class="col-lg-2">
                    <el-select maxlength="20" v-model="searchForm.status" placeholder="请选择">
                        <el-option value="">请选择</el-option>
                        <el-option
                            v-for="item in [{value:'0',label:'正常'},{value:'1',label:'冻结'},{value:'2',label:'禁用'}]"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                  </div> 
                  <label class="col-form-label">手机号：</label>
                  <div class="col-lg-2">
                      <input type="text" class="form-control" v-model="searchForm.phone" placeholder="请输入">
                  </div>               
                  <label class="col-form-label">邮箱：</label>
                  <div class="col-lg-2">
                      <input type="text" class="form-control" v-model="searchForm.email" placeholder="请输入">
                  </div>
                  <b-button :pressed="false" variant="btn btn-primary font-weight-bold font-size-sm py-3 px-8 mr-2 " @click="search()"><span><i
                  class="flaticon-search-magnifier-interface-symbol"></i><span>查 询</span></span></b-button>
                  <b-button :pressed="false" variant="btn btn-light font-weight-bold font-size-sm py-3 px-8 mr-2 " @click="resetAll()">
                  <span><i class="flaticon2-refresh"></i><span>重 置</span></span></b-button> 
              </div>
            </div> 
            <div class="m-portlet__foot m-portlet__no-border m-portlet__foot--fit">
              <div class="m-form__actions m-form__actions--solid">
                <div class="row">
                  <div class="col m--align-left">
                    <button class="btn btn-light-primary font-weight-bold font-size-sm py-3 px-8 mr-2 mr-2 "
                    v-permission="{ action: '/oauthAccount/add', effect: 'display' }"
                    @click="addOauthAccount">
                      <span><i class="la la-plus la-lg"></i><span>新建账户</span></span>
                    </button>
                  </div>
                  <div class="col text-right">
                    <a class="btn btn-text-dark-50 btn-icon-primary font-weight-bold btn-hover-bg-light mr-3" href="javascript:void(0)" 
                    v-permission="{ action: '/oauthAccountTenant/add', effect: 'display' }"
                    @click="setOauthAccountTenant">
                      <b-spinner small variant="primary"  type="grow"></b-spinner>
                      绑定租户
                    </a>   
                  </div>
                </div>
              </div>
            </div>             
          </div>
      </div>
      <!--分页组件-->
      <el-table style="width: 100%" stripe border @selection-change="handleSelectionChange" highlight-current-row :data="accountDataList" >
        <template slot="empty">
          <el-empty description="暂无数据"></el-empty>
        </template>
        <!-- 复选框 -->
        <el-table-column type="selection" width="40"></el-table-column>
        <el-table-column label="序号" min-width="50">
          <template slot-scope="scope">
            {{scope.$index+1}} 
          </template>
        </el-table-column>
        <el-table-column align="left" fixed="left" show-overflow-tooltip label="头像" width="80">
            <template slot-scope="scope">
                <div class="symbol symbol-60 symbol-circle symbol-xl-30">
                  <div class="symbol-label" :style="{
                      backgroundImage: scope.row.smallPic
                        ? `url(${scope.row.smallPic})`
                        : `url(${defaultSmall})`,
                    }">
                  </div>
                  <i class="symbol-badge symbol-badge-bottom bg-success"></i>
                </div>
            </template>
        </el-table-column>
        <el-table-column align="center" prop="account" label="账号" min-width="100"></el-table-column>
        <el-table-column align="center" prop="name" label="姓名" min-width="180">
          <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <div class="symbol symbol-60 symbol-circle symbol-xl-60">
              <div class="symbol-label" :style="{
                  backgroundImage: scope.row.smallPic
                    ? `url(${scope.row.smallPic})`
                    : `url(${defaultSmall})`,
                }">
              </div>
              <i class="symbol-badge symbol-badge-bottom bg-success"></i>
            </div>
            <p>姓名: {{ scope.row.name }}</p>
            <p>账号: {{ scope.row.account }}</p>
            <p>邮箱: {{ scope.row.email }}</p>
            <p>手机号: {{ scope.row.phone }}</p>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">{{ scope.row.name }}</el-tag>
            </div>
          </el-popover>
        </template>
        </el-table-column>
        <el-table-column align="center" :formatter="formatterTypes" show-overflow-tooltip prop="oauthAccountTypes"  label="类型" min-width="200">
          
        </el-table-column>
        <el-table-column align="center" prop="status"  label="状态" min-width="110">
          <template slot-scope="scope">
            <div v-if="scope.row.status == 0" class="symbol symbol-40 symbol-circle symbol-light-success">
                <span class="symbol-label font-size-h8">正常</span>
            </div>
            <div v-if="scope.row.status == 1" class="symbol symbol-40 symbol-circle symbol-light-warning">
                <span class="symbol-label font-size-h8">冻结</span>
            </div>
            <div v-if="scope.row.status == 2" class="symbol symbol-40 symbol-circle symbol-light-danger">
              <span class="symbol-label font-size-h8">冻结</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="email"  label="邮箱" min-width="200"></el-table-column>
        <el-table-column align="center" prop="phone" label="联系电话" min-width="180"></el-table-column>
        <el-table-column align="center" prop="createTime"  label="注册时间" min-width="160"></el-table-column>
        <el-table-column align="center" prop="updateTime"  label="最后修改时间" min-width="160"></el-table-column>
        <el-table-column align="center" prop="lastLoginTime"  label="上次登录时间" min-width="160"></el-table-column>
        <el-table-column align="center" label="操作" fixed="left" min-width="460">
          <template slot-scope="scope">
            <!--scope.row当前行的对象-->
            <button @click="getOauthAccountDetail(scope.row)" class="btn btn-link" title="详情">详 情</button>
            <button class="btn btn-link"
            v-permission="{ action: '/oauthAccount/update', effect: 'disabled' }"
            @click="updateOauthAccount(scope.row)"> 
              <span><i class="la la-pen-alt"></i><span>编 辑</span></span>
            </button>
            <button class="btn btn-link-danger"
            v-permission="{ action: '/oauthAccount/freeze', effect: 'disabled' }"
            @click="freeze(scope.row)"> 
              <span><i class="far fa-trash-alt"></i><span>冻 结</span></span>
            </button>
            <button v-if="scope.row.status == 1" @click="unfreeze(scope.row)" class="btn btn-link" title="解冻"
            v-permission="{ action: '/oauthAccount/unfreeze', effect: 'disabled' }"
            >解 冻</button>
            <button @click="initRoleinfo(scope.row)" class="btn btn-link" title="角色权限">角色权限</button>
            <button @click="resetAccountPwd(scope.row)" class="btn btn-link"
            v-permission="{ action: '/oauthAccount/restPwd', effect: 'disabled' }"
            title="重置密码">重置密码</button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          hide-on-single-page   
          @size-change="handleSizeChange"        
          @current-change="handleCurrentChange"  
          :current-page="pageNo"                
          :page-sizes="[5, 10, 30, 50]"          
          :page-size="pageSize"			  
          layout="->,total, sizes, prev, pager, next, jumper"
          :total="totalCount">		
        </el-pagination>
      </div>
    </div>
    <AccountAdd ref="accountAddRef" @change="search"></AccountAdd><!--采用父窗口关闭传递的方法-->
    <AccountUpdate ref="accountUpdateRef" @change="search"></AccountUpdate><!--采用父窗口关闭传递的方法-->
    <AccountDetail ref="accountDetailRef"></AccountDetail>
    <AccountRole ref="accountRoleRef"></AccountRole>
    <AccountTenant ref="accountTenantRef"></AccountTenant>
</div>

</template>

<script>
import { SET_BREADCRUMB } from "@/store/breadcrumbs.module";
import AccountAdd from "@/view/oauth/oauth-account/oauth-account-add.vue";
import AccountUpdate from "@/view/oauth/oauth-account/oauth-account-update.vue";
import AccountDetail from "@/view/oauth/oauth-account/oauth-account-detail.vue";
import AccountRole from "@/view/oauth/oauth-account/account-role.vue";
import AccountTenant from "@/view/oauth/oauth-account/account-tenant.vue";
import Swal from "sweetalert2";
import apiUtil from "@/core/util/apiUtil.js"; 
import { handleNotify,handleAlert,handleConfirm,showWating,closeWating} from "@/core/util/jehcUtil.js";
export default {
  data(){
    return{
      defaultSmall:"media/users/default.jpg",
      searchForm:{accountTypeIdTemp:"",accountTypeId: "",name:"",account:"",typeCondition:"",status:"",email:"",phone:"",},
      typeList:[],
      accountDataList:[],
      sels: [], //当前选框选中的值
      pageNo:1,      // 默认当前是第一页
      pageSize:5,    // 当前每页的数据是5条
      totalCount:0   // 总数默认为0
    }
  },
  components: {
      AccountAdd,
      AccountUpdate,
      AccountDetail,
      AccountRole,
      AccountTenant,
  },
  watch: {
      "searchForm.accountTypeIdTemp":{//监听字段变化
          handler:function(newVal,old){
              if(newVal){
                  this.searchForm.accountTypeId = newVal.join(",");
              }
          }
      },
  },
  mounted() {
      this.$store.dispatch(SET_BREADCRUMB, [{ title: "账户管理" }]);
      this.initList();   // 按当前的页号和每页的数据量进行查询
      this.initTypeList();
  },
  methods:{
    initList(){
      showWating({renderBody:"tableBody"});
      var params = {};
      params.usePageNo = true;//采用第几页进行分页（兼容）
      params.pageSize = this.pageSize;//页面显示记录条数，在页面显示每页显示多少项的时候
      params.pageNo = this.pageNo;//开始的记录序号   
      params.searchJson = JSON.stringify(this.searchForm);//为form元素     
      apiUtil.queryPage(process.env.VUE_APP_OAUTH_API+"/oauthAccount/list", params).then(({ data }) => {
        this.accountDataList = data.data;//给结果集赋值
        this.totalCount = data.total;// 获取当前数据的总数    
      });
    },      
    handleSelectionChange(sels) {//获取选中的值
      this.sels = sels;
      // console.log("选中的值",sels.map((item) => item.id));
    },
    addOauthAccount(){//新建
      this.$refs.accountAddRef.showModal()
    },
    updateOauthAccount(row){// 更新
      this.$refs.accountUpdateRef.showModal(row.id);
    },
    freeze(row){ // 删除用户
      // 冻结前提示
      this.$confirm("确认冻结所选记录吗?", "提示", {type: "warning",}).then(() => {
        apiUtil.delete(process.env.VUE_APP_OAUTH_API+"/oauthAccount/freeze/"+row.id).then(data=>{
          if(data.data.success){
            handleAlert("冻结成功", "success", 3);
            this.search();
          }else {
            handleAlert("冻结失败", "error", 3);
          }
        });
      }).catch(()=>{});//注意这里，这里是重点！！！;        
    },
    unfreeze(row){
      let id = row.id;
      let account = row.account;
      let name = row.name;
      // 重置密码前提示
      this.$confirm('确定要解冻姓名：'+name+'，登录账户：'+account+'的状态？', "提示", {type: "warning",}).then(() => {
        // 根据后台想要的参数格式选择
        // console.log(ids.join(",")); //1,2,3,4
        // console.log(ids); //[1,2,3,4]
        var params = {};
        apiUtil.delete(process.env.VUE_APP_OAUTH_API+"/oauthAccount/unfreeze/"+id,{params}).then(data=>{
          if(data.data.success){
            handleAlert("解冻成功", "success", 3);
            this.search();
          }else {
            handleAlert("解冻失败", "error", 3);
          }
        });
      }).catch(()=>{});//注意这里，这里是重点！！！; 
    },
    handleSizeChange(val) { // 修改每页所存数据量的值所触发的函数
      this.pageSize = val;  // 修改页的大小
      this.initList();       // 按新的pageNo和pageSize进行查询
    },
    handleCurrentChange(val) { // 修改当前页所触发的函数
      this.pageNo = val;       // 更新当前的页
      this.initList();          // 按新的pageNo和pageSize进行查询
    },
    search(){
      this.pageNo = 1;       // 更新当前的页
      this.initList();          // 按新的pageNo和pageSize进行查询
    },
    resetAll(){
      Object.assign(this.$data.searchForm, this.$options.data().searchForm);
      this.search();
    },
    getOauthAccountDetail(row){
      this.$refs.accountDetailRef.showModal(row.id);
    },
    initRoleinfo(row){//角色窗体
      this.$refs.accountRoleRef.showModal(row.id);
    },
    formatterTypes(row, column){
      let oauthAccountTypes  = row.oauthAccountTypes;
      let accountTypeText = null;
      if(null != oauthAccountTypes){
          for(var i =0; i < oauthAccountTypes.length;i++){
              if(null == accountTypeText){
                  accountTypeText = oauthAccountTypes[i].name;
              }else{
                accountTypeText = accountTypeText+","+oauthAccountTypes[i].name;
              }
          }
      }
      return accountTypeText;
    },
    resetAccountPwd(row){//重置密码
      let id = row.id;
      let account = row.account;
      let name = row.name;
      // 重置密码前提示
      this.$confirm('确定要重置姓名：'+name+'，登录账户：'+account+'的密码？', "提示", {type: "warning",}).then(() => {
        // 根据后台想要的参数格式选择
        // console.log(ids.join(",")); //1,2,3,4
        // console.log(ids); //[1,2,3,4]
        var params = {accountId:id};
        apiUtil.post(process.env.VUE_APP_OAUTH_API+"/oauthAccount/restPwd",params).then(data=>{
          if(data.data.success){
            handleAlert("重置成功", "success", 3);
            this.search();
          }else {
            handleAlert("重置失败", "error", 3);
          }
        });
      }).catch(()=>{});//注意这里，这里是重点！！！; 
    },
    initTypeList(){
      let params = {};
      apiUtil.query(process.env.VUE_APP_OAUTH_API+"/oauthAccountType/listAll", params).then(({ data }) => {
          this.typeList = data.data;
      });
    },
    setOauthAccountTenant(){
      if(this.sels.length != 1){
        handleAlert("请选择一条数据", "warning", 3)
        return;
      }
      let accountTypeId = this.sels.map((item) => item.accountTypeId);
      let account = this.sels.map((item) => item.account);
      this.$refs.accountTenantRef.showModal(accountTypeId.join(","),account.join(","));
    },
  }
};
</script>